<?php
/**
 * 配置缓存命令：替代 php artisan config:cache
 */

namespace Jammiest\SwigeCore\Console\Commands\Cache;

use Jammiest\SwigeCore\Console\Commands\Command;
use Jammiest\SwigeCore\Tools\Path;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'config:cache')]
class ConfigCommand extends Command
{
    protected function configure()
    {
        $this->setDescription('缓存配置文件中');
    }

    protected function execute(InputInterface $input, OutputInterface $output):int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('缓存配置文件');
        
        try {
            $cacheFile = Path::getBasePath('storage/framework/cache/config.php');
            // $cacheFile = storage_path('framework/cache/config.php');
            $cacheDir = dirname($cacheFile);
            
            if (!is_dir($cacheDir)) {
                mkdir($cacheDir, 0755, true);
            }
            
            // 加载所有配置并合并
            $config = $this->loadAllConfigs();
            
            // 写入缓存文件
            $cacheContent = '<?php return ' . var_export($config, true) . ';';
            file_put_contents($cacheFile, $cacheContent);
            
            $io->success('配置缓存已生成: ' . $cacheFile);
            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            $io->error('配置缓存失败: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }

    private function loadAllConfigs()
    {
        $config = [];
        $configFiles = glob(Path::getBasePath('config/*.php'));
        // $configFiles = glob(config_path('*.php'));
        
        foreach ($configFiles as $file) {
            $key = basename($file, '.php');
            $config[$key] = require $file;
        }
        
        return $config;
    }
}